<?php
/*
 module:		推广中心
 create_time:	2022-03-30 11:29:39
 author:   陕西格创
 contact:
*/

namespace app\api\controller;

use app\api\service\ZhExtensionService;
use app\backend\model\ZhInvit;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use EasyWeChat\Factory;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Encoding\Encoding;

class ZhExtension extends Common {
    
    /**
     * @api {get} /ZhExtension/add 01、添加
     * @apiGroup ZhExtension
     * @apiVersion 1.0.0
     * @apiDescription  创建数据
     
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (输入参数：) {string}
     
     * @apiParam (失败返回参数：) {object}     	array 返回结果集
     * @apiParam (失败返回参数：) {string}     	array.status 返回错误码  201
     * @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}     	array 返回结果集
     * @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}     	array.msg 返回成功消息
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":"操作成功"}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"操作失败"}
     */
    function add(){
        $wxapp_id = $this->request->get('wxapp_id');
//        $uId      = $this->request->get('uid');;
        $op     = $this->request->get('op');
        $bgm_info=ZhInvit::find(1)->column("image");
        $bgm_url="";
        if(count($bgm_info)>0){
            $bgm_url=$bgm_info[0];
        }

        if($op=="test"){
            $uId=512;
        }else{
            $uId = $this->getUid();
        }

        $type     = $this->request->get('type','','serach_in');
        if(!$wxapp_id){
            return $this->ajaxReturn($this->errorCode,'缺少平台参数');
        }
        $sysSiteData = SysSiteModel::where('wxapp_id',$wxapp_id)->find()->toArray();
        if(!$sysSiteData){
            return $this->ajaxReturn($this->errorCode,'平台参数未配置');
        }
        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find()->toArray();
        if(!$user){
            return $this->ajaxReturn($this->errorCode,'未知用户');
        }
        $config = [
            'app_id' => $sysSiteData['app_id'],
            'secret' => $sysSiteData['app_secret'],
            
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log'           => [
                'level' => 'debug',
                'file'  => __DIR__.'/wechat.log',
            ],
        ];
        $path  ='pages/home/home';
        $param ='p_id='.$uId ;//用户id
        $res   = [];
        
        if(!$user['qr_code'] && $type == 'wx'){

            $app      = Factory::miniProgram($config);
            $response = $app->app_code->getUnlimit($param, [
                'page'  => $path,
                'width' => 600,
            ]);
            // $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例，失败为数组或你指定的 API 返回类型
            
            // 保存小程序码到文件
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->save(public_path() . 'qrcode',time() . '_' . $uId);
                
                MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])
                           ->update(['qr_code'=> '/qrcode/' . $filename ]);
                $res['avatar'] = $user['avatar'];
                $res['qr_code'] = $this->request->domain() . '/qrcode/' . $filename;
            }else{
                return $this->ajaxReturn($this->errorCode,'小程序未发布，无法生成小程序码',['bgm_url'=>$bgm_url]);
            }
        }elseif ((!$user['app_code'] && $type == 'app') || (!$user['h_code'] && $type == 'h5')){
            // Create a basic QR code
            $writer = new PngWriter();
            if($type == 'app'){
                $data = $uId;
            }else{
                $data = $this->request->domain() . '/h5/?p_id=' . $uId;
              
            }
            $qrCode = QrCode::create($data)
                            ->setEncoding(new Encoding('UTF-8'))
                            ->setSize(300)
                            ->setMargin(10);
            $result = $writer->write($qrCode);
    
            $result->saveToFile(__DIR__.'/qrcode.png');
//            $qrCode = new QrCode($uId);
//            $qrCode->setSize(300);
//            $qrCode->setMargin(10);
//
//            // Set advanced options
//            $qrCode->setWriterByName('png');
//            $qrCode->setEncoding('UTF-8');
//
//            // Directly output the QR code
//            header('Content-Type: '.$qrCode->getContentType());
//            //            echo $qrCode->writeString();
//
//            // Save it to a file
            $pathName = time() . '_' . $uId . '.png';
            if($type == 'app'){
                $path = public_path() . 'appcode/' . $pathName;
                $codeUrl = '/appcode/' . $pathName;
                $upData = [
                    'app_code'=> $codeUrl
                ];
            }else{
                $path = public_path() . 'hcode/' . $pathName;
                $codeUrl = '/hcode/' . $pathName;
                $upData = [
                    'h_code'=> $codeUrl
                ];
            }
            
            $result->saveToFile($path);
            
//            $qrCode->writeFile($path);
//            $dataUri = $qrCode->writeDataUri();
            $dataUri = $result->getDataUri();
//            $dataUri= '';
            if($dataUri){
                MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])
                           ->update($upData);
                $res['avatar'] = $user['avatar'] ?: '';
                $res['qr_code'] = $this->request->domain() . $codeUrl;
            }
        }else{
            $res['avatar'] = $user['avatar'];
            if($type == 'wx'){
                $res['qr_code'] = $this->request->domain() . $user['qr_code'];
            }elseif ($type == 'app'){
                $res['qr_code'] = $this->request->domain() . $user['app_code'];
            }
            elseif ($type == 'h5'){
                $res['qr_code'] = $this->request->domain() . $user['h_code'];
            }
            
        }
        if( $res['avatar'] ==""){
            $res['avatar'] ="https://xcx.xizihongniang.cn/uploads/admin/202404/6610cecba9bae.png";
        }
        $res['bgm_url']=$bgm_url;
        return $this->ajaxReturn($this->successCode,'操作成功',$res);
    }
    
    
    
}

